//
//  OMPersonalInfoViewController.m
//  OMENGO
//
//  Created by 梁尚嘉 on 2017/1/10.
//  Copyright © 2017年 Kamfat. All rights reserved.
//

#import "OMPersonalInfoViewController.h"

#import "OMPersonalAvatarTableCell.h"
#import "KTEleInputTableCell.h"

#import "XHPhotographyHelper.h"
#import <MobileCoreServices/MobileCoreServices.h>
@interface OMPersonalInfoViewController ()
@property (nonatomic, strong) OMAccount *account;

@property (nonatomic, strong) OMPersonalAvatarTableCell *avatarCell;
@property (nonatomic, strong) KTEleInputTableCell *nicknameCell;
@property (nonatomic, strong) NSArray <NSArray<BaseTableCell*> *>*cellArray;

@property (nonatomic, strong) XHPhotographyHelper *photographyHelper;
@end

@implementation OMPersonalInfoViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self setupUI];
    [self getInfo];
}

- (void)setupUI
{
    self.title = @"个人资料";
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    _avatarCell = [OMPersonalAvatarTableCell tableViewCellWithTableView:self.tableView];
    [_avatarCell.avatarImageView kt_imageWithURLStr:KTSystemStorageSingleton.account.avatar placeHolder:nil withSize:CGSizeZero];
    _nicknameCell = [KTEleInputTableCell tableViewCellWithTableView:self.tableView];
    _nicknameCell.elementLabel.text = @"昵称";
    _nicknameCell.inputTF.enabled = true;
    _nicknameCell.inputTF.textAlignment = NSTextAlignmentLeft;
    _nicknameCell.inputTF.text = KTSystemStorageSingleton.account.nickname;

    _cellArray = @[@[self.avatarCell, self.nicknameCell]];
}

- (void)reloadDataFromNetWork
{
    [self getInfo];
}




/**
 获取个人信息(暂时弃用 URL需要更换)
 */
- (void)getInfo
{
    return;//<----删除这行
    [KTHttpUtils GET:@"需要更换url"
          completion:^(id responseObject, BOOL isSuccess, NSString *message) {

    }];
}

- (void)configure
{
    [self.avatarCell configureCellWithObj:self.account];
//    self.pointCell.inputTF.text = [NSString stringWithFormat:@"%ld分",self.account.point];
}

///图片管理器
- (XHPhotographyHelper *)photographyHelper
{
    if (!_photographyHelper) {
        _photographyHelper = [[XHPhotographyHelper alloc] init];
    }
    return _photographyHelper;
}

#pragma mark - tableview delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.cellArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [(id)self.cellArray[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.cellArray[indexPath.section][indexPath.row];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [(id)self.cellArray[indexPath.section][indexPath.row].class cellHeight];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return SM_SIZE(25);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return DBL_EPSILON;
}

- (BaseTableCell *)cellAtIndexPath:(NSIndexPath *)indexPath
{
    return self.cellArray[indexPath.section][indexPath.row];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[self cellAtIndexPath:indexPath] isKindOfClass:[OMPersonalAvatarTableCell class]]) {
        [self getPhoto];
    }
}

#pragma mark - Actions

/**
  头像cell点击回调方法
 */
- (void)getPhoto
{
    @weakify(self);
    NSMutableArray *menuList = [NSMutableArray arrayWithCapacity:1];
    [menuList addObject:[DownSheetModel downSheetModelWithIcon:nil andIcon_on:nil andTitle:@"从相册中选择"]];
    [menuList addObject:[DownSheetModel downSheetModelWithIcon:nil andIcon_on:nil andTitle:@"拍照"]];
    DownSheet *sheet = [[DownSheet alloc]initWithlist:menuList height:0];
    [sheet setOnSelectAction:^(NSInteger selectedIndex) {
        @strongify(self);
        [self setupPhotoFromLibraryWithSelectedIndex:selectedIndex];
    }];
    [sheet showInView:nil];
}

/**
 选择相册或相机
 */
- (void)setupPhotoFromLibraryWithSelectedIndex:(NSUInteger)selectedIndex
{
    @weakify(self);
    void (^PickerMediaBlock)(UIImage *image, NSDictionary *editingInfo) = ^(UIImage *image, NSDictionary *editingInfo) {
        @strongify(self);
        if (image) {
            [self uploadPicturesWithImage:image];
        } else {
            if (!editingInfo)
                return ;
            NSString *mediaType = [editingInfo objectForKey: UIImagePickerControllerMediaType];
            NSString *videoPath;
            NSURL *videoUrl;
            if (CFStringCompare ((__bridge CFStringRef) mediaType, kUTTypeMovie, 0) == kCFCompareEqualTo) {
                videoUrl = (NSURL*)[editingInfo objectForKey:UIImagePickerControllerMediaURL];
                videoPath = [videoUrl path];

            } else {
                [self uploadPicturesWithImage:[editingInfo valueForKey:UIImagePickerControllerEditedImage]];
            }
        }
    };

    switch (selectedIndex) {
        case 0: {
            [self.photographyHelper showOnPickerViewControllerSourceType:UIImagePickerControllerSourceTypePhotoLibrary onViewController:self compled:PickerMediaBlock];
            break;
        }
        case 1: {
            [self.photographyHelper showOnPickerViewControllerSourceType:UIImagePickerControllerSourceTypeCamera onViewController:self compled:PickerMediaBlock];
            break;
        }
        default:
            break;
    }
}

///上传头像
- (void)uploadPicturesWithImage:(UIImage *)image
{
    [OMHUD HUDShieldLoading:@"正在上传头像"];
    image = [UIImage imageWithData:UIImageJPEGRepresentation(image, 0.1)];
    [Storage saveImageInCache:image onCompletion:^(BOOL isSuccess, NSString *uuid) {

        [KTHttpUtils UPLOADImage:@"member/avatar"
                      parameters:nil
                        fileURLs:@[[Storage imageURLInCacheWithName:uuid]]
                        progress:^(NSProgress *progress) {
                            [OMHUD HUDShieldProgress:progress.fractionCompleted status:@"正在上传图片"];
        } completion:^(id responseObject, BOOL isSuccess, NSString *message) {
            if (isSuccess) {

                OMAccount *account = KTSystemStorageSingleton.account;
                account.avatar = responseObject[OMDataKey];
                KTSystemStorageSingleton.account = account;
                [Storage setLogin:YES];
                [Storage removeImageInCacheWithName:uuid];
                [self.avatarCell.avatarImageView setImage:image];
//                [KTHttpUtils autoLoginOnResult:nil];
                [OMHUD HUDHide];
            }else {
                [OMHUD HUDError:message];
            }
        }];
    }];


}
@end
